<template>
  <Layout>
    <Sider ref="siderCollapsed" class="app-main-side-menu" hide-trigger collapsible :collapsed-width="80" :width="240"
           v-model="isCollapsed">
      <div class="app-main-logo">
        <img
            :src="!isCollapsed?'https://file.iviewui.com/admin-pro-dist/img/logo-dark.ab519d9f.png':'https://file.iviewui.com/admin-pro-dist/img/logo-small.4a34a883.png'"
            alt="" height="80%">
      </div>
      <Menu :open-names="openNames" :active-name="activeName" ref="sideMenu" theme="dark" width="auto"
            :class="menuitemClasses" accordion
            @on-select="turnToPage"
            v-show="!isCollapsed">
        <Submenu :name="item.name" v-for="(item,index) in menuList" :key="index" v-if="item.children">
          <template slot="title">
            <Icon :type="item.icon"/>
            {{ item.title }}
          </template>
          <MenuItem :name="subItem.name" v-for="(subItem,subIndex) in item.children"
                    :key="subIndex">
            {{ subItem.title }}
          </MenuItem>
        </Submenu>
        <MenuItem v-else :name="item.name">{{ item.title }}</MenuItem>
      </Menu>
      <div class="app-menu" v-show="isCollapsed">
        <div v-for="(item,index) in menuList" :key="index">
          <Dropdown class="menu-side-collapse" placement="right-start" v-if="item.children" @on-click="turnToPage">
            <div :class="['menu-side-collapse-item',collapsedIsActive(item.name)]">
              <Icon :type="item.icon" size="20"/>
            </div>
            <DropdownMenu slot="list" style="width:150px;">
              <DropdownItem :name="subItem.name" :selected="subItem.name===selectedTag.name" :key="subIndex"
                            v-for="(subItem,subIndex) in item.children">
                {{ subItem.title }}
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
          <div :class="['menu-side-collapse-item',collapsedIsActive(item.name)]" v-else @click="turnToPage(item.name)">
            <Icon :type="item.icon" size="20"/>
          </div>
        </div>
      </div>
    </Sider>

    <Layout>
      <Header class="app-main-header">
        <div class="icon-item" @click="collapsedSider">
          <Icon :class="rotateIcon" type="md-menu" size="20"></Icon>
        </div>
        <div class="app-main-userInfo">
          <Select v-model="model1" style="width:200px" @on-change="handleChange">
            <Option v-for="item in productList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
          <span class="user-info-text" style="margin-left:30px">欢迎，{{ user.username }}</span>
          <Avatar class="user-avatar">{{ user.username[0] }}</Avatar>
          <div class="icon-item">
            <Icon type="ios-power" @click="handleLoginOut"/>
          </div>
        </div>
      </Header>
      <Content>
        <div id="tag-nav-wrapper">
          <Tabs type="card" :value="selectedTag.name" @on-click="turnToPage">
            <TabPane v-for="(tab,index) in tagNavList" :key="index" :label="(h)=>{return labelCreate(h,tab)}"
                     :name="tab.name"></TabPane>
          </Tabs>
          <Dropdown placement="bottom-end" transfer @on-click="closeBatchTag">
            <div class="tag-close-wrap">
              <Icon type="ios-arrow-down"></Icon>
            </div>
            <DropdownMenu slot="list">
              <DropdownItem name="other">
                <Icon type="md-close"/>
                关闭其他
              </DropdownItem>
              <DropdownItem name="all">
                <Icon type="md-close-circle"/>
                全部关闭
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </div>
        <div class="content-wrapper">
          <keep-alive :include="cacheList">
            <router-view v-if="isRouterAlive"></router-view>
          </keep-alive>
        </div>
      </Content>
    </Layout>
  </Layout>
</template>

<script>
import menuList from '@/utils/menu'
import {mapMutations, mapState} from 'vuex'
import {projectList} from "@/utils/api";
export default {
  name: 'Main',
  data() {
    return {
      isCollapsed: false,
      openNames: [],
      productList: [],
      tabs: 50,
      user: JSON.parse(localStorage.getItem("userInfo")),
      menuList,
      isRouterAlive: true,
      model1: ""
    }
  },
  provide() {
    return {
      reload:this.reload
    }
  },
  computed: {
    ...mapState('tagNav', {
      tagNavList: 'list',
      selectedTag: 'selectedTag'
    }),

    activeName() {
      return this.$route.meta.parent || this.$route.name
    },

    rotateIcon() {
      return [
        'menu-icon',
        this.isCollapsed ? 'rotate-icon' : ''
      ]
    },
    menuitemClasses() {
      return [
        'app-menu',
        this.isCollapsed ? 'collapsed-menu' : ''
      ]
    },
    cacheList() {
      const list = ['home', ...this.tagNavList.map((item) => {
        return item.name
      })]
      return list
    },
  },
  created() {
    const stroeProjectId = localStorage.getItem("project")
    if (stroeProjectId) {
      this.model1 = parseInt(stroeProjectId);
      this.getProjects();
    } else {
      this.getProjects();
    }
    this.$store.commit("updateSelectProject", stroeProjectId)
    this.setHeight();
  },

  mounted() {
    this.openMenu()
    this.$nextTick(() => {
      window.onresize = () => {
        this.setHeight()
      }
    })

  },

  watch: {
    '$route'(route) {
      let {meta, params, query, name} = route
      if (!route.meta.hasOwnProperty('parent')) {
        this.addTag({meta, params, query, name})
        this.openMenu()
      } else {
        this.enterSubTag({meta, params, query, name})
      }
    }
  },
  methods: {
    ...mapMutations('tagNav', [
      'addTag',
      'closeTag',
      'closeBatchTag',
      'enterSubTag'
    ]),

    /**
     * @author              TianYu
     * @description         设置右侧内容区域高度
     */
    setHeight() {
      let height = (document.documentElement.clientHeight || document.body.clientHeight)
      this.$store.commit('SET_PAGE_HEIGHT', height)
    },

    getProjects(){
        projectList().then(res=> {
        this.productList = res.data.data.projects;
      })
    },

    labelCreate(h, tab) {
      return h('div', [
        h('span', tab.meta.title),
        h('Icon', {
          style: {
            'margin': '0 0 0 8px',
            'display': tab.meta.hasOwnProperty('fixed') ? 'none' : 'inline-block'
          },
          props: {
            type: 'md-close'
          },
          on: {
            click: (event) => {
              event.stopPropagation()
              this.closeTag(tab.name)
            }
          }
        })
      ])
    },

    collapsedIsActive(name) {
      return this.openNames.indexOf(name) > -1 ? 'ivu-menu-item-active' : ''
    },

    collapsedSider() {
      this.$refs.siderCollapsed.toggleCollapse()
    },

    turnToPage(routerName) {
      if (this.selectedTag.name !== routerName) {
        this.$router.push({
          name: routerName
        })
      }
    },

    openMenu() {
      if (this.selectedTag.meta) {
        this.openNames = []
        this.getParentNodes(this.menuList, this.selectedTag.meta.parent || this.selectedTag.name)
        this.$nextTick(() => {
          this.$refs.sideMenu.updateOpened()
          this.$refs.sideMenu.updateActiveName()
        })
      } else {
        this.addTag({meta: {title: '主页', fixed: true}, name: 'home'})
      }
    },

    /**
     * 根据Tree 的子节点获取所有父节点
     */
    getParentNodes(data, node) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].name === node) {
          return true
        } else {
          if (data[i].children) {
            if (this.getParentNodes(data[i].children, node)) {
              this.openNames.unshift(data[i].name)
              return true
            }
          }
        }
      }
    },

    handleLoginOut() {
      localStorage.removeItem("userInfo")
      localStorage.removeItem("token")
      this.$router.push({name: "login"})
      this.$Message.success('退出登录成功');
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
        console.log('reload')
      })
    },
    handleChange(e){
      this.model1 = e;
      localStorage.setItem("project", e);
      this.$store.commit("updateSelectProject", e);
      // localStorage.setItem("project_id", e);
      // this.$router.replace("/")
      // this.closeBatchTag("all");
      // this.reload()
    }
  }
}
</script>

<style lang="stylus">
#tag-nav-wrapper
  padding 6px 0
  margin 0 12px
  background: #F0F0F0
  display flex

  .tag-close-wrap
    width 32px
    height 32px
    line-height 32px
    text-align center
    background-color #fff
    border-radius 2px
    cursor pointer

  .ivu-tabs-card
    flex 1

    .ivu-tabs-bar
      border-bottom none
      margin-bottom 0

      .ivu-tabs-nav .ivu-tabs-tab
        border 0
        background #fff
        border-radius 0

.content-wrapper
  padding 18px
  height calc(88vh - 16px)

.app-main-logo
  background-color #191a23
  height 63px
  line-height 63px
  text-align center

  &.collapse
    width 64px

.app-main-side-menu.ivu-layout-sider
  min-height 80vh
  background-color #191a23
  box-shadow 2px 0 6px rgba(0, 21, 41, .35)

  .menu-side-collapse
    display block

    .ivu-select-dropdown
      margin 5px 0 5px 3px
      background-color #191a23

      .ivu-dropdown-item
        color rgba(255, 255, 255, 0.7)

        &.ivu-dropdown-item-selected
          background-color #2d8cf0
          color #fff

        &:hover
          color #fff
          background-color #191a23

  .menu-side-collapse-item
    width 80px
    display inline-block
    text-align center
    padding 14px 0
    height 52px
    cursor pointer
    color rgba(255, 255, 255, 0.7)
    white-space nowrap

    &.ivu-menu-item-active
      color #fff !important

    .ivu-icon
      vertical-align middle

    &:hover
      color #fff

  .app-menu
    height calc(100vh - 64px)
    overflow-y auto

  .app-menu span
    display: inline-block;
    overflow: hidden;
    width: 69px;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
    transition: width .2s ease .2s;

  .app-menu.collapsed-menu span
    width 0px
    transition width 0.2s ease

  .app-menu.collapsed-menu i
    transform translateX(5px)
    transition font-size 0.2s ease 0.2s, transform 0.2s ease 0.2s
    vertical-align middle
    font-size 22px

.app-main-header.ivu-layout-header
  background-color #fff
  padding 0

  .icon-item
    display inline-block
    position relative
    vertical-align top
    height 64px
    padding 0 20px

    &:hover
      cursor pointer
      background-color #f8f8f9

  .menu-icon
    cursor: pointer

  .rotate-icon
    transform: rotate(-90deg)

  .app-main-userInfo
    float right
    vertical-align middle

    .user-info-text
      font-size 12px

    .user-avatar
      border-radius 50%
      vertical-align middle
      background-color #2d8cf0
      margin 0 10px 0 15px
      font-size 14px

    .app-theme
      margin-left 3px
</style>
